package be.pluyckx.batteryprogress.logging;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Date;

import be.pluyckx.batteryprogress.application.Constants;

/**
 * Created by Philip Luyckx on 9/08/13.
 */
public class LogcatDump {
  private final File mDirectory;

  public LogcatDump(File directory) {
    mDirectory = directory;

    if (!mDirectory.exists()) {
      mDirectory.mkdirs();
    } else if (!mDirectory.isDirectory()) {
      throw new IllegalArgumentException("The parameter must be a directory!");
    }
  }


  public void autoDumpFileThreaded(Callback callback) {
    if (Constants.getStoreHistory()) {
      dumpFileThreaded(callback);
    }
  }

  public void dumpFileThreaded(final Callback callback) {
    new Thread(new Runnable() {
      @Override
      public void run() {
        dumpFile(callback);
      }
    }).start();
  }

  public void autoDumpFile(Callback callback) {
    if (Constants.getStoreLogs()) {
      dumpFile(callback);
    }
  }

  public void dumpFile(Callback callback) {
    File file = generateFile();
    if (file == null) {
      if (callback != null) {
        callback.done(false);
      }
      return;
    }

    Process process = null;
    BufferedReader reader = null;
    FileWriter writer = null;

    try {
      // process = Runtime.getRuntime().exec("logcat -d -f \"" + file.getAbsolutePath() + "\"");
      process = Runtime.getRuntime().exec("logcat -d -v time *:W *:E *:F *:V *:I");
      reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
      writer = new FileWriter(file);

      char buff[] = new char[1024];
      int read = 0;

      while ((read = reader.read(buff)) != -1) {
        writer.write(buff, 0, read);
      }

      if(callback != null) {
        callback.done(true);
      }
    } catch (IOException ex) {
      ex.printStackTrace();
      if (callback != null) {
        callback.done(false);
      }
      return;
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException ex) {
          ex.printStackTrace();
        }
      }
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException ex) {
          ex.printStackTrace();
        }
      }
      if (process != null) {
        process.destroy();
      }
    }

    try {
      process = Runtime.getRuntime().exec("logcat -c");
      try {
        process.waitFor();
      } catch (InterruptedException ex) {
        ex.printStackTrace();
      }
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      if (process != null) {
        process.destroy();
      }
    }
  }

  private File generateFile() {
    Date now = new Date(System.currentTimeMillis());
    String filename = Constants.dateTimeFileFormat.format(now);
    File file;
    int index = 0;

    do {
      file = new File(mDirectory, filename + (index != 0 ? Integer.toString(index) : "") + ".log");
    } while (file.exists());

    try {
      file.createNewFile();
    } catch (IOException ex) {
      ex.printStackTrace();
      file = null;
    }

    return file;
  }

  public static interface Callback {
    public void done(boolean writeSuccess);
  }
}
